from exts import db
from common import constant
from common.base_model import BasicModelMixin, CompanyMixin, CreateWithShortNameMixin, \
    UpdateWithShortNameMixin, DeleteMixin, CreateMixin, UpdateMixin

MIDDLE_DB_STR_LEN = constant.MIDDLE_DB_STR_LEN
LONG_DB_STR_LEN = constant.LONG_DB_STR_LEN
COMMON_DECIMAL = constant.COMMON_DECIMAL

# 颜色 尺寸
spec_attrs_template: [dict] = [{
    "spec": {"id": 1, "name": "颜色"},
    "attrs": [{"id": 1, "name": "红"}, {"id": 1, "name": "蓝"}]
}, {
    "spec": {"id": 1, "name": "尺寸"},
    "attrs": [{"id": 1, "name": "S"}, {"id": 1, "name": "M"}]
}]


class Spu(db.Model, BasicModelMixin, CompanyMixin, CreateWithShortNameMixin, UpdateWithShortNameMixin, DeleteMixin):
    __tablename__ = 'spu'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(MIDDLE_DB_STR_LEN), nullable=False)
    short_name = db.Column(db.String(MIDDLE_DB_STR_LEN))

    is_multiple_spec = db.Column(db.Boolean, default=False)  # 是否多规格
    spec_string = db.Column(db.String(LONG_DB_STR_LEN))  # 规格字符串
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))  # 分类
    brand_id = db.Column(db.Integer, db.ForeignKey('brand.id'))  # 品牌
    spec_attrs = db.Column(db.JSON)
    exp = db.Column(db.String(LONG_DB_STR_LEN))  # 保质期
    barcode = db.Column(db.String(MIDDLE_DB_STR_LEN))  # 条形码
    is_multiple_spec_price = db.Column(db.Boolean, default=False)  # 是否多规格价格

    category = db.relationship("Category")
    brand = db.relationship("Brand")
    # 级联删除关系
    spu_to_units = db.relationship('SpuToUnit', backref='spu', cascade="all, delete-orphan")
    # 级联删除sku
    skus = db.relationship('Sku', backref='spu', cascade="all, delete-orphan")


# 换算关系: 商品与单位1对多
class SpuToUnit(db.Model, BasicModelMixin, CompanyMixin, CreateMixin, UpdateMixin, DeleteMixin):
    __tablename__ = 'spu_to_unit'

    id = db.Column(db.Integer, primary_key=True)
    spu_id = db.Column(db.Integer, db.ForeignKey('spu.id'), nullable=False)
    unit_id = db.Column(db.Integer, db.ForeignKey('unit.id'))
    is_base_unit = db.Column(db.Boolean, default=False)
    num_of_base_unit = db.Column(db.DECIMAL(20, COMMON_DECIMAL), default=1)

    unit = db.relationship("Unit", foreign_keys='SpuToUnit.unit_id')


# # 商品图片
# class SpuToFile(db.Model, BasicModelMixin, CompanyMixin, CreateMixin, UpdateMixin, DeleteMixin):
#     __tablename__ = 'spu_to_file'
#
#     spu_id = db.Column(db.Integer, db.ForeignKey('spu.id'), primary_key=True)
#     file_id = db.Column(db.Integer, db.ForeignKey('file.id'), primary_key=True)

    # 暂时不需要，通过手动获取 spu_files
    # procedure = db.relationship(
    #     Procedure,
    #     backref=backref("procedure_files", cascade="all, delete-orphan")
    # )
    # file = relationship("File")


"""规格json
    >>> {
        '机身颜色'：['香槟金'，'樱花粉'],
        '内存'：['16G'，'32G']
    }
    
    >>> {
        'spec_id'：['attr_id'，'attr_id'],
        'spec_id'：['attr_id'，'attr_id']
    }
    
    spec_attrs: []
    """
